const {
    getProject,
    updateProject,
    createProject,
    destroyProject,
    changeStatusProject
} = require('../service/project'),
    { updateToQiniu, returnInfo, fileUploadLegel } = require('../lib/utils'),
    { nanoid } = require('nanoid'),
    { IMAGE_UPLOAD, API } = require('../config/err_config'),
    { qiniu } = require('../config/config'),
    path = require('path');
class Project{
    async getProjectC(ctx){
        try {
            const { id } = ctx.request.body;
            let retrunMess = await getProject(id);
            ctx.body = returnInfo(API.GET_PROJECT_SUCCESS,retrunMess);
        } catch (error) {
            console.log(error);
            ctx.body = returnInfo(API.GET_PROJECT_ERROR);
        }
    }
    async createProject(ctx){
        let projectimg = '';
        let isLegel = fileUploadLegel(ctx);
        if(isLegel){
            const files = Object.entries(ctx.request.files),
                  { projectname, projectlink } = ctx.request.body;
            let extname = path.extname(files[0][1].name),
                filePath = files[0][1].path,
                fileName = `projectphoto${nanoid()}${extname}`;
            try {
                updateToQiniu(filePath,fileName);
                projectimg = `${qiniu.bucket.blogsimg.domain}/${fileName}`;
            } catch (error) {
                console.log(error);
                ctx.body = IMAGE_UPLOAD.UPLOAD_ERROR;
            }   
            try {
                let returnMess = await createProject({projectlink,projectimg,projectname})
                ctx.body = returnMess ? returnInfo(API.CREATE_PROJECT_SUCESS)
                    : returnInfo(API.CREATE_PROJECT_ERROR)
            } catch (error) {
                console.log(error);
                ctx.body = returnInfo(API.CREATE_PROJECT_ERROR)
            }  
        }else{
            ctx.body = returnInfo(IMAGE_UPLOAD.UPLOAD_ERROR)
            return;
        }
    }
    async destroyProject(ctx){
        let { id } = ctx.request.body;
        try {
            let returnMess = await destroyProject(id);
            ctx.body = returnMess ? returnInfo(API.DESTROY_PROJECT_SUCCESS)
                : returnInfo(API.DESTROY_PROJECT_ERROR)
        } catch (error) {
            console.log(error);
            ctx.body = returnInfo(API.DESTROY_PROJECT_ERROR);
        }    
    }
    async updateProject(ctx){}
    async changeStatusProject(ctx){}
}
module.exports = new Project();    